package netty.client;

import netty.model.MethodInvokeMeta;
import netty.util.WrapMethodUtils;
import org.springframework.beans.factory.config.AbstractFactoryBean;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class RPCProxyFactoryBean extends AbstractFactoryBean<Object> implements InvocationHandler
{
	private Class interfaceClass;

	private NettyClient client;

	public void setClient(NettyClient client)
	{
		this.client = client;
	}

	public void setInterfaceClass(Class interfaceClass)
	{
		this.interfaceClass = interfaceClass;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
		throws Throwable
	{
		final MethodInvokeMeta mim = WrapMethodUtils.readMethod(interfaceClass, method, args);
		return client.remoteCall(mim, 0);
	}

	@Override
	protected Object createInstance()
		throws Exception
	{
		return Proxy.newProxyInstance(interfaceClass.getClassLoader(),
			new Class[] {interfaceClass}, this);
	}

	@Override
	public Class<?> getObjectType()
	{
		return interfaceClass;
	}
}
